
class Magnifier {
    constructor() {
        this.getJdian();
        this.onMouse();
    };

    getJdian() {//获取节点
        this.box = document.querySelector('#box');
        this.big = document.querySelector('#big');
        this.mask = document.querySelector('#mask');
        this.bigImg = document.querySelector('#img');
        this.small = document.querySelector('#small');
        // console.log(this.box, this.big, this.mask, this.bigImg, this.small);
    };

    onMouse() {//移入 移出 移动
        small.onmouseover = this.overFn.bind(this);
        small.onmouseout = this.outFn.bind(this);
        small.onmousemove = this.moveFn.bind(this);
    };

    overFn() { //移入显示
        this.big.style.display = 'block';
        this.mask.style.display = 'block';
    };

    outFn() { //移出隐藏
        this.big.style.display = 'none';
        this.mask.style.display = 'none';
    };

    moveFn = (event) => {
        //设置目标距离

        // console.log(event.clientX);
        // console.log(event.clientY);
        // console.log(this.mask.offsetWidth/ 2);
        let targetX = (event.pageX - this.box.offsetLeft) - this.mask.offsetWidth / 2;
        let targetY = (event.pageY - this.box.offsetTop) - this.mask.offsetHeight / 2;
        // console.log(targetY);
        //大图片的宽减去大盒子的宽
        let maxX = this.small.offsetWidth - this.mask.offsetWidth;
        let maxY = this.small.offsetHeight - this.mask.offsetHeight;

        if (targetX < 0) targetX = 0;
        if (targetY < 0) targetY = 0;

        if (targetX > maxX) targetX = maxX;
        if (targetY > maxY) targetY = maxY;

        //给遮罩绑定坐标 使其在页面中动起来
        this.mask.style.left = targetX + 'px';
        this.mask.style.top = targetY + 'px';

        let imgMaxX = this.bigImg.offsetWidth - this.big.offsetWidth;
        let imgMaxY = this.bigImg.offsetHeight - this.big.offsetHeight;
        // console.log(this.imgMaxX);
        //img移动的距离 = mask移动的距离 / mask移动的最大距离 * img移动的最大距离
        this.bigImg.style.top = -(targetY / maxY * imgMaxY) + 'px';
        this.bigImg.style.left = - (targetX / maxX * imgMaxX) + 'px';
    };
};
new Magnifier();


